package sketch.ui;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionListener;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.UIManager;

import sketch.doc.Point;
import sketch.doc.SketchContainer;
import sketch.doc.Stroke;

/**
 *
 * @author  zhengwt
 */
public class SketchSampler extends javax.swing.JFrame {

    public static int ID_NUM = 20;
	public static String FILE_PREFIX = "seg";
	public static final String CONFIRM_OVERWRITE_MSG = "File already exists, overwrite?!";
	public static final String CONFIRM_OVERWRITE_TITLE = "Alert!";
	public static final String CONFIRM_SAVE_MSG = "File saved successfully.";
	public static final String CONFIRM_SAVE_TITLE = "Message";

	public SketchSampler() {
		initProperties();
        initComponents();
    }

    private void initProperties() {
    	Properties p = new Properties();
    	try {
			p.load(new FileInputStream(new File("ui.properties")));

			ID_NUM = Integer.parseInt(p.getProperty("ID_NUM"));
			FILE_PREFIX = p.getProperty("FILE_PREFIX");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void initComponents() {

    	//TODO: initialization
    	setTitle("Sketch Sampler v0.1");
    	setResizable(false);
//

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(getJPanelCommand(), org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .add(getJPanelSketch(), org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(getJPanelCommand(), org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(getJPanelSketch(), org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        pack();


        //TODO: later init
//        getJTextFieldName().setfo
        setSize(720,740);
        setLocation(50, -10);
    }

    public static void main(String args[]) {
    	try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			e.printStackTrace();
		}
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SketchSampler().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButtonClear;
    private javax.swing.JButton jButtonDir;
    private javax.swing.JButton jButtonNext;
    private javax.swing.JButton jButtonPrev;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JComboBox jComboBoxID;
    private javax.swing.JLabel jLabelDir;
    private javax.swing.JLabel jLabelID;
    private javax.swing.JLabel jLabelName;
    private javax.swing.JPanel jPanelCommand;
    private javax.swing.JPanel jPanelSketch;
    private javax.swing.JTextField jTextFieldDir;
    private javax.swing.JTextField jTextFieldName;

	public javax.swing.JButton getJButtonClear() {
		if (jButtonClear == null) {
			jButtonClear = new JButton();
			jButtonClear.setText("Clear");

			jButtonClear.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					clearSketch();
				}

	        });
		}
		return jButtonClear;
	}

	private void clearSketch() {
		SketchContainer.get().clear();
		repaint();
	}

	public javax.swing.JButton getJButtonDir() {
		if (jButtonDir == null) {
			jButtonDir = new JButton();
			jButtonDir.setText("...");

			jButtonDir.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					JFileChooser ch = new JFileChooser(".");
					ch.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
					ch.showOpenDialog(SketchSampler.this);
					File dir = ch.getSelectedFile();
					if (dir != null)
						getJTextFieldDir().setText(dir.getAbsolutePath());
				}

			});
		}
		return jButtonDir;
	}

	public javax.swing.JButton getJButtonNext() {
		if (jButtonNext == null) {
			jButtonNext = new JButton();
			jButtonNext.setText("Next");
			jButtonNext.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					increaseID();
					clearSketch();
				}

			});
		}
		return jButtonNext;
	}

	private void increaseID() {
		int cur = getID();
		if (cur < ID_NUM);
			setID(cur + 1);
	}

	private void decreaseID() {
		int cur = getID();
		if (cur > 1)
			setID(cur - 1);
	}

	private int getID() {
		return Integer.parseInt(getJComboBoxID().getSelectedItem().toString());
	}

	private void setID(int id) {
		getJComboBoxID().setSelectedItem(Integer.toString(id));
	}

	public javax.swing.JButton getJButtonPrev() {
		if (jButtonPrev == null) {
			jButtonPrev = new JButton();
			jButtonPrev.setText("Prev");

			jButtonPrev.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					decreaseID();
					clearSketch();
				}

			});
		}
		return jButtonPrev;
	}

	public javax.swing.JButton getJButtonSave() {
		if (jButtonSave == null) {
			jButtonSave = new JButton();
			jButtonSave.setText("Save");

			jButtonSave.addActionListener(new ActionListener() {

				public void actionPerformed(ActionEvent e) {
					String filename = getFileName();
					System.out.println("save to file: " + filename);
					File file = new File(filename);
					if (file.exists()) {
						int result = JOptionPane.showConfirmDialog(SketchSampler.this, CONFIRM_OVERWRITE_MSG, CONFIRM_OVERWRITE_TITLE, JOptionPane.YES_NO_OPTION);
						if (result == 1) // result NO
							return;
					}
					SketchContainer.get().save(file);
					JOptionPane.showConfirmDialog(SketchSampler.this, CONFIRM_SAVE_MSG, CONFIRM_SAVE_TITLE, JOptionPane.PLAIN_MESSAGE);
				}

			});
		}
		return jButtonSave;
	}

	private String getFileName() {
		return getJTextFieldDir().getText()
		+ "\\" + getJTextFieldName().getText() + "." + FILE_PREFIX + "." + getID();
	}

	public javax.swing.JComboBox getJComboBoxID() {
		if (jComboBoxID == null) {
			jComboBoxID = new JComboBox();
			jComboBoxID.setModel(new DefaultComboBoxModel(getIDs()));
		}
		return jComboBoxID;
	}

	private String[] getIDs() {
		String[] s = new String[ID_NUM];
		for (int i = 0; i < s.length; i++) {
			s[i] = Integer.toString(i+1);
		}
		return s;
	}

	public javax.swing.JLabel getJLabelDir() {
		if (jLabelDir == null) {
			jLabelDir = new JLabel();
			jLabelDir.setText("Save directory");
		}
		return jLabelDir;
	}

	public javax.swing.JLabel getJLabelID() {
		if (jLabelID == null) {
			jLabelID = new JLabel();
			jLabelID.setText("Sample ID:");
		}
		return jLabelID;
	}

	public javax.swing.JLabel getJLabelName() {
		if (jLabelName == null) {
			jLabelName = new JLabel();
			jLabelName.setText("Your name:");
		}
		return jLabelName;
	}

	public javax.swing.JPanel getJPanelCommand() {
		if (jPanelCommand == null) {
			jPanelCommand = new JPanel();

			jPanelCommand.setBorder(javax.swing.BorderFactory.createTitledBorder("Command"));

	        org.jdesktop.layout.GroupLayout jPanelCommandLayout = new org.jdesktop.layout.GroupLayout(jPanelCommand);
	        jPanelCommand.setLayout(jPanelCommandLayout);
	        jPanelCommandLayout.setHorizontalGroup(
	            jPanelCommandLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
	            .add(jPanelCommandLayout.createSequentialGroup()
	                .addContainerGap()
	                .add(jPanelCommandLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
	                    .add(jPanelCommandLayout.createSequentialGroup()
	                        .add(getJLabelName())
	                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                        .add(getJTextFieldName(), org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 180, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
	                    .add(jPanelCommandLayout.createSequentialGroup()
	                        .add(getJLabelID())
	                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                        .add(getJComboBoxID(), 0, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	                    .add(jPanelCommandLayout.createSequentialGroup()
	                        .add(getJLabelDir())
	                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                        .add(getJTextFieldDir())))
	                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                .add(jPanelCommandLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
	                    .add(jPanelCommandLayout.createSequentialGroup()
	                        .add(getJButtonDir(), org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 45, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
	                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, 146, Short.MAX_VALUE)
	                        .add(getJButtonSave())
	                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                        .add(getJButtonClear()))
	                    .add(jPanelCommandLayout.createSequentialGroup()
	                        .add(getJButtonPrev())
	                        .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                        .add(getJButtonNext())))
	                .addContainerGap())
	        );
	        jPanelCommandLayout.setVerticalGroup(
	            jPanelCommandLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
	            .add(jPanelCommandLayout.createSequentialGroup()
	                .addContainerGap()
	                .add(jPanelCommandLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
	                    .add(getJLabelName())
	                    .add(getJTextFieldName(), org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
	                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                .add(jPanelCommandLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
	                    .add(getJLabelID())
	                    .add(getJComboBoxID(), org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
	                    .add(getJButtonPrev())
	                    .add(getJButtonNext()))
	                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
	                .add(jPanelCommandLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
	                    .add(getJLabelDir())
	                    .add(getJTextFieldDir(), org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
	                    .add(getJButtonDir())
	                    .add(getJButtonClear())
	                    .add(getJButtonSave()))
	                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
	        );
		}
		return jPanelCommand;
	}

	public javax.swing.JPanel getJPanelSketch() {
		if (jPanelSketch == null) {
			jPanelSketch = new JPanel()  {

				public void paint(Graphics arg0) {
					super.paint(arg0);
					Graphics2D g2 = (Graphics2D) arg0;

					SketchContainer.get().draw(g2);
				}

			};

			jPanelSketch.addMouseMotionListener(new MouseMotionListener() {

				public void mouseDragged(MouseEvent e) {
					SketchContainer.get().appendPoint(new Point(e.getX(), e.getY()));
					SketchContainer.get().drawCurrent((Graphics2D)getJPanelSketch().getGraphics());
				}

				public void mouseMoved(MouseEvent e) {
					// TODO Auto-generated method stub

				}
			});

			jPanelSketch.addMouseListener(new MouseAdapter() {

				@Override
				public void mousePressed(MouseEvent e) {
					super.mousePressed(e);
					SketchContainer.get().appendPoint(new Point(e.getX(), e.getY()));
				}

				@Override
				public void mouseReleased(MouseEvent e) {
					super.mouseReleased(e);

					SketchContainer.get().appendPoint(new Point(e.getX(), e.getY()));
					Stroke s = SketchContainer.get().fetchStroke();
					SketchContainer.get().open().addStroke(s);

					repaint();
				}

			});

			jPanelSketch.setBackground(new java.awt.Color(255, 255, 255));
	        jPanelSketch.setBorder(javax.swing.BorderFactory.createTitledBorder("Sketch"));
	        org.jdesktop.layout.GroupLayout jPanelSketchLayout = new org.jdesktop.layout.GroupLayout(jPanelSketch);
	        jPanelSketch.setLayout(jPanelSketchLayout);
	        jPanelSketchLayout.setHorizontalGroup(
	            jPanelSketchLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
	            .add(0, 576, Short.MAX_VALUE)
	        );
	        jPanelSketchLayout.setVerticalGroup(
	            jPanelSketchLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
	            .add(0, 500, Short.MAX_VALUE)
	        );

		}
		return jPanelSketch;
	}

	public javax.swing.JTextField getJTextFieldDir() {
		if (jTextFieldDir == null) {
			jTextFieldDir = new JTextField();
			jTextFieldDir.setEditable(false);

			jTextFieldDir.setText(new File(".").getAbsolutePath());
		}
		return jTextFieldDir;
	}

	public javax.swing.JTextField getJTextFieldName() {
		if (jTextFieldName == null) {
			jTextFieldName = new JTextField();
			jTextFieldName.setToolTipText("Please anter your name (in short form, such as zhengwt)");
		}
		return jTextFieldName;
	}



}

